<template>
  <div class="order-statistics-container">
    <div class="statistics-header-section">
      <div class="statistics-title-section">
        <h2 class="page-title">订单数据统计</h2>
        <p class="page-description">图形化展示酒店订单数据和收入情况</p>
      </div>

      <div class="statistics-filters">
        <div class="filter-item">
          <span class="filter-label">时间范围：</span>
          <a-range-picker 
            v-model:value="dateRange" 
            :format="'YYYY-MM-DD'" 
            @change="handleDateRangeChange"
            :placeholder="['开始日期', '结束日期']"
            class="date-picker"
          />
        </div>

        <div class="filter-item">
          <span class="filter-label">数据周期：</span>
          <a-radio-group v-model:value="dataPeriod" button-style="solid" @change="updateCharts" class="period-selector">
            <a-radio-button value="month">月度</a-radio-button>
            <a-radio-button value="quarter">季度</a-radio-button>
            <a-radio-button value="year">年度</a-radio-button>
          </a-radio-group>
        </div>

        <div class="filter-item action-item">
          <a-button @click="goBack" type="primary">
            <template #icon><rollback-outlined /></template>
            返回订单管理
          </a-button>
        </div>
      </div>
    </div>

    <a-row :gutter="[16, 16]" class="chart-row">
      <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
        <a-card :bordered="false" class="chart-card">
          <template #title>
            <div class="chart-header">
              <h3>{{ periodTitle }}订单数量</h3>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="orderCountOption" autoresize />
          </div>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
        <a-card :bordered="false" class="chart-card">
          <template #title>
            <div class="chart-header">
              <h3>{{ periodTitle }}收入金额</h3>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="revenueOption" autoresize />
          </div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="[16, 16]" class="chart-row">
      <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
        <a-card :bordered="false" class="chart-card">
          <template #title>
            <div class="chart-header">
              <h3>订单状态分布</h3>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="orderStatusOption" autoresize />
          </div>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
        <a-card :bordered="false" class="chart-card">
          <template #title>
            <div class="chart-header">
              <h3>房型订单分布</h3>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="roomTypeOption" autoresize />
          </div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="[16, 16]" class="chart-row">
      <a-col :span="24">
        <a-card :bordered="false" class="chart-card">
          <template #title>
            <div class="chart-header">
              <h3>收入与订单趋势</h3>
            </div>
          </template>
          <div class="chart-container">
            <v-chart class="chart" :option="trendOption" autoresize />
          </div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { RollbackOutlined } from '@ant-design/icons-vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart, LineChart, PieChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
} from 'echarts/components';
import VChart from 'vue-echarts';
import dayjs from 'dayjs';
import { useHotelStore } from '@/stores/hotelStrore';
import { apiGetOrderStatistics, apiGetBookingStats, apiGetRoomTypeBookingStats } from '@/api/admin-api';
import * as echarts from 'echarts/core';

// 注册 ECharts 组件
use([
  CanvasRenderer,
  BarChart,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
]);

const router = useRouter();
const hotelStore = useHotelStore();

// 图表周期设置 - 合并为一个变量
const dataPeriod = ref('month');
// 默认显示最近6个月的数据
const dateRange = ref([dayjs().subtract(6, 'month').startOf('month'), dayjs().endOf('month')]);

// 模拟数据 - 实际应用中应该从API获取
const orderData = reactive({
  // 月度订单数量
  monthlyOrderCount: [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330],
  // 月度收入
  monthlyRevenue: [18000, 19000, 16000, 21000, 14000, 25000, 23000, 19000, 22000, 28000, 32000, 36000],
  // 年度订单数量
  yearlyOrderCount: [1500, 1800, 2200, 2500, 2800],
  // 年度收入
  yearlyRevenue: [220000, 250000, 300000, 350000, 400000],
  // 订单状态分布
  orderStatus: [
    { value: 235, name: '已下单' },
    { value: 274, name: '已入住' },
    { value: 310, name: '已完成' },
    { value: 35, name: '已取消' }
  ],
  // 房型订单分布
  roomTypeDistribution: [
    { value: 320, name: '标准间' },
    { value: 240, name: '豪华间' },
    { value: 149, name: '家庭套房' },
    { value: 100, name: '总统套房' },
    { value: 59, name: '商务间' }
  ],
  // 趋势数据
  trendData: {
    dates: ['2023-01', '2023-02', '2023-03', '2023-04', '2023-05', '2023-06', 
            '2023-07', '2023-08', '2023-09', '2023-10', '2023-11', '2023-12'],
    orderCounts: [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330],
    revenue: [18000, 19000, 16000, 21000, 14000, 25000, 23000, 19000, 22000, 28000, 32000, 36000]
  }
});

// 获取订单统计数据
async function fetchOrderStatistics() {
  try {
    // 获取酒店ID
    const hotelId = hotelStore.safeHotelId;
    if (!hotelId) {
      message.warning('未获取到酒店ID，请先设置酒店信息');
      return;
    }
    
    // 显示加载状态
    message.loading({ content: '正在加载数据...', key: 'loadingStats' });
    
    // 获取订单状态分布数据
    const statsRes:any = await apiGetBookingStats(hotelId);
    console.log('订单状态分布数据:', statsRes);
    
    if (statsRes?.code === 200) {
      const statsData = statsRes.data || {};
      // 更新订单状态分布数据
      orderData.orderStatus = [
        { value: parseInt(statsData.booked || 0), name: '已下单' },
        { value: parseInt(statsData.checked_in || 0), name: '已入住' },
        { value: parseInt(statsData.confirmed || 0), name: '已完成' },
        { value: parseInt(statsData.cancelled || 0), name: '已取消' }
      ];
      
      console.log('处理后的订单状态数据:', orderData.orderStatus);
    } else {
      console.error('获取订单状态分布数据失败:', statsRes);
      message.error('获取订单状态分布数据失败');
    }
    
    // 获取房型订单分布数据
    const roomTypeRes: any = await apiGetRoomTypeBookingStats(hotelId);
    console.log('房型订单分布数据:', roomTypeRes);
    
    if (roomTypeRes?.code === 200) {
      const roomTypeData = roomTypeRes.data || [];
      if (Array.isArray(roomTypeData) && roomTypeData.length > 0) {
        orderData.roomTypeDistribution = roomTypeData.map(item => ({
          value: parseInt(item.count || 0),
          name: item.roomType || '未知房型'
        }));
        
        console.log('处理后的房型分布数据:', orderData.roomTypeDistribution);
      }
    } else {
      console.error('获取房型订单分布数据失败:', roomTypeRes);
      message.error('获取房型订单分布数据失败');
    }
    
    // 获取订单图表统计数据
    const params: any = {
      period: dataPeriod.value
    };
    
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0]?.format('YYYY-MM-DD');
      params.endDate = dateRange.value[1]?.format('YYYY-MM-DD');
      
      // 确保按月显示，添加参数
      params.groupBy = 'month';
    }
    
    const chartRes: any = await apiGetOrderStatistics(hotelId, params);
    if (chartRes?.code === 200) {
      const chartData = chartRes.data || {};
      
      // 更新月度订单数量数据
      if (chartData.orderCounts && Array.isArray(chartData.orderCounts)) {
        orderData.monthlyOrderCount = chartData.orderCounts;
      }
      
      // 更新月度收入数据
      if (chartData.revenue && Array.isArray(chartData.revenue)) {
        orderData.monthlyRevenue = chartData.revenue;
      }
      
      // 更新年度数据
      if (chartData.yearlyOrderCount && Array.isArray(chartData.yearlyOrderCount)) {
        orderData.yearlyOrderCount = chartData.yearlyOrderCount;
      }
      
      if (chartData.yearlyRevenue && Array.isArray(chartData.yearlyRevenue)) {
        orderData.yearlyRevenue = chartData.yearlyRevenue;
      }
      
      // 更新趋势数据
      if (chartData.dates && Array.isArray(chartData.dates)) {
        // 确保日期数据格式正确
        orderData.trendData.dates = chartData.dates;
        orderData.trendData.orderCounts = chartData.orderCounts || [];
        orderData.trendData.revenue = chartData.revenue || [];
        
        console.log('获取到的图表数据:', {
          dates: orderData.trendData.dates,
          orderCounts: orderData.trendData.orderCounts,
          revenue: orderData.trendData.revenue
        });
      }
      
      message.success({ content: '数据加载成功', key: 'loadingStats' });
    } else {
      message.error({ content: '获取图表数据失败', key: 'loadingStats' });
    }
    
  } catch (error) {
    console.error('获取订单统计数据失败:', error);
    message.error({ content: '获取订单统计数据失败', key: 'loadingStats' });
  }
}

// 刷新数据
function refreshData() {
  message.loading({ content: '正在刷新数据...', key: 'refreshData' });
  fetchOrderStatistics().then(() => {
    message.success({ content: '数据已刷新', key: 'refreshData' });
  });
}

// 更新图表
function updateCharts() {
  // 根据选择的周期更新图表数据
  console.log('更新图表:', dataPeriod.value);
  fetchOrderStatistics();
}

// 处理日期范围变化
function handleDateRangeChange() {
  // 根据选择的日期范围更新趋势图表
  console.log('日期范围变化:', dateRange.value);
  if (dateRange.value && dateRange.value.length === 2) {
    // 确保日期范围有效
    const startDate = dateRange.value[0];
    const endDate = dateRange.value[1];
    
    if (startDate && endDate) {
      // 如果日期范围过大（超过24个月），提示用户
      const monthsDiff = endDate.diff(startDate, 'month');
      if (monthsDiff > 24) {
        message.warning('选择的日期范围过大，建议选择24个月以内的范围以获得更好的展示效果');
      }
      
      // 调用API获取指定日期范围的数据
      fetchOrderStatistics();
    }
  }
}

// 返回订单管理
function goBack() {
  router.push('/admin/order');
}

onMounted( async () => {
  if (!hotelStore.isInitialized) {
    await hotelStore.getHotelInfo();
  }
  
  if (hotelStore.safeHotelId) {
    fetchOrderStatistics();
  } else {
    message.warning('未找到酒店ID，无法加载订单统计信息');
  }
  
});

// 订单数量图表配置
const orderCountOption = computed(() => {
  let xAxisData: string[] = [];
  let seriesData: number[] = [];
  
  // 使用后端返回的实际日期数据
  if (orderData.trendData && orderData.trendData.dates && orderData.trendData.dates.length > 0) {
    xAxisData = orderData.trendData.dates;
    seriesData = orderData.trendData.orderCounts || [];
  } else {
    // 默认数据，仅在API返回失败时使用
    if (dataPeriod.value === 'month') {
      xAxisData = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
    } else if (dataPeriod.value === 'quarter') {
      xAxisData = ['第一季度', '第二季度', '第三季度', '第四季度'];
    } else if (dataPeriod.value === 'year') {
      const currentYear = new Date().getFullYear();
      xAxisData = [
        (currentYear - 4).toString(),
        (currentYear - 3).toString(),
        (currentYear - 2).toString(),
        (currentYear - 1).toString(),
        currentYear.toString()
      ];
    }
    seriesData = orderData.monthlyOrderCount;
  }
  
  // 优化图表显示
  const fewDataPoints = xAxisData.length <= 3;
  const barWidth = fewDataPoints ? 60 : 'auto'; // 少量数据点时设置固定宽度
  const minValue = Math.max(0, Math.min(...seriesData) - 1); // 设置Y轴最小值为数据最小值减1，但不小于0
  
  return {
    title: {
      text: '订单数量统计',
      left: 'center',
      show: false
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: {c} 单'
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLabel: {
        interval: 0,
        rotate: xAxisData.length > 4 ? 30 : 0, // 数据多时才旋转标签
        formatter: (value: string) => {
          // 如果是YYYY-MM格式，转换为更友好的显示
          if (/^\d{4}-\d{2}$/.test(value)) {
            const [year, month] = value.split('-');
            return `${year}年${month}月`;
          }
          return value;
        }
      },
      axisLine: {
        show: true
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      name: '订单数量',
      nameTextStyle: {
        padding: [0, 0, 0, 30]
      },
      min: fewDataPoints ? minValue : null, // 少量数据点时设置最小值
      minInterval: 1, // 保证Y轴刻度是整数
      splitNumber: fewDataPoints ? 5 : 'auto' // 控制Y轴分割段数
    },
    series: [
      {
        name: '订单数量',
        type: 'bar',
        data: seriesData,
        barWidth: barWidth, // 设置柱子宽度
        barMaxWidth: 100, // 设置柱子最大宽度
        barGap: '30%', // 增加柱子间距
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        },
        // 少量数据点时添加标签
        label: {
          show: fewDataPoints,
          position: 'top',
          formatter: '{c} 单',
          fontSize: 14
        }
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    }
  };
});

// 收入金额图表配置
const revenueOption = computed(() => {
  let xAxisData: string[] = [];
  let seriesData: number[] = [];
  
  // 使用后端返回的实际日期数据
  if (orderData.trendData && orderData.trendData.dates && orderData.trendData.dates.length > 0) {
    xAxisData = orderData.trendData.dates;
    seriesData = orderData.trendData.revenue || [];
  } else {
    // 默认数据，仅在API返回失败时使用
    if (dataPeriod.value === 'month') {
      xAxisData = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
    } else if (dataPeriod.value === 'quarter') {
      xAxisData = ['第一季度', '第二季度', '第三季度', '第四季度'];
    } else if (dataPeriod.value === 'year') {
      const currentYear = new Date().getFullYear();
      xAxisData = [
        (currentYear - 4).toString(),
        (currentYear - 3).toString(),
        (currentYear - 2).toString(),
        (currentYear - 1).toString(),
        currentYear.toString()
      ];
    }
    seriesData = orderData.monthlyRevenue;
  }
  
  // 优化图表显示
  const fewDataPoints = xAxisData.length <= 3;
  const barWidth = fewDataPoints ? 60 : 'auto'; // 少量数据点时设置固定宽度
  const minValue = Math.max(0, Math.min(...seriesData) - 100); // 设置Y轴最小值为数据最小值减100，但不小于0
  
  return {
    title: {
      text: '收入金额统计',
      left: 'center',
      show: false
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{b}: ¥{c}'
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLabel: {
        interval: 0,
        rotate: xAxisData.length > 4 ? 30 : 0, // 数据多时才旋转标签
        formatter: (value: string) => {
          // 如果是YYYY-MM格式，转换为更友好的显示
          if (/^\d{4}-\d{2}$/.test(value)) {
            const [year, month] = value.split('-');
            return `${year}年${month}月`;
          }
          return value;
        }
      },
      axisLine: {
        show: true
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      name: '收入金额 (¥)',
      nameTextStyle: {
        padding: [0, 0, 0, 30]
      },
      axisLabel: {
        formatter: '{value} 元'
      },
      min: fewDataPoints ? minValue : null, // 少量数据点时设置最小值
      splitNumber: fewDataPoints ? 5 : 'auto' // 控制Y轴分割段数
    },
    series: [
      {
        name: '收入金额',
        type: 'bar',
        data: seriesData,
        barWidth: barWidth, // 设置柱子宽度
        barMaxWidth: 100, // 设置柱子最大宽度
        barGap: '30%', // 增加柱子间距
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#67e0e3' },
            { offset: 0.5, color: '#32c5e9' },
            { offset: 1, color: '#32c5e9' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#37a2da' },
              { offset: 0.7, color: '#37a2da' },
              { offset: 1, color: '#67e0e3' }
            ])
          }
        },
        // 少量数据点时添加标签
        label: {
          show: fewDataPoints,
          position: 'top',
          formatter: '¥{c}',
          fontSize: 14
        }
      }
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    }
  };
});

// 订单状态分布图表配置
const orderStatusOption = computed(() => {
  // 过滤掉值为0的数据，避免显示空状态
  const validOrderStatus = orderData.orderStatus.filter(item => item.value > 0);
  
  // 如果没有有效数据，显示提示
  if (validOrderStatus.length === 0) {
    return {
      title: {
        text: '暂无订单数据',
        left: 'center',
        top: 'middle',
        textStyle: {
          color: '#999',
          fontSize: 16
        }
      }
    };
  }
  
  // 计算总订单数
  const totalOrders = validOrderStatus.reduce((sum, item) => sum + item.value, 0);
  
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} 单 ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'horizontal',
      bottom: 0,
      left: 'center',
      itemWidth: 10,
      itemHeight: 10,
      itemGap: 20,
      formatter: function(name: string): string {
        const item = validOrderStatus.find(item => item.name === name);
        if (item) {
          // 计算百分比
          const percent = ((item.value / totalOrders) * 100).toFixed(1);
          return `${name}: ${item.value} 单 (${percent}%)`;
        }
        return name;
      },
      textStyle: {
        fontSize: 12
      },
      data: validOrderStatus.map(item => item.name)
    },
    series: [
      {
        name: '订单状态',
        type: 'pie',
        radius: ['40%', '65%'],
        center: ['50%', '40%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}: {c} 单\n{d}%',
          fontSize: 12
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: true,
          length: 15,
          length2: 10,
          smooth: true
        },
        data: validOrderStatus,
        color: ['#5470c6', '#91cc75', '#ee6666', '#fac858']
      }
    ]
  };
});

// 房型订单分布图表配置
const roomTypeOption = computed(() => {
  // 过滤掉值为0的数据，避免显示空状态
  const validRoomTypes = orderData.roomTypeDistribution.filter(item => item.value > 0);
  
  // 如果没有有效数据，显示提示
  if (validRoomTypes.length === 0) {
    return {
      title: {
        text: '暂无房型数据',
        left: 'center',
        top: 'middle',
        textStyle: {
          color: '#999',
          fontSize: 16
        }
      }
    };
  }
  
  // 计算总订单数
  const totalRoomOrders = validRoomTypes.reduce((sum, item) => sum + item.value, 0);
  
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} 单 ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'horizontal',
      bottom: 0,
      left: 'center',
      itemWidth: 10,
      itemHeight: 10,
      itemGap: 20,
      pageButtonPosition: 'end',
      pageButtonGap: 5,
      pageButtonItemGap: 5,
      pageIconColor: '#888',
      pageIconInactiveColor: '#ccc',
      pageIconSize: 15,
      pageTextStyle: {
        color: '#666'
      },
      formatter: function(name: string): string {
        const item = validRoomTypes.find(item => item.name === name);
        if (item) {
          // 计算百分比
          const percent = ((item.value / totalRoomOrders) * 100).toFixed(1);
          return `${name}: ${item.value} 单 (${percent}%)`;
        }
        return name;
      },
      textStyle: {
        fontSize: 12
      },
      data: validRoomTypes.map(item => item.name)
    },
    series: [
      {
        name: '房型分布',
        type: 'pie',
        radius: ['40%', '65%'],
        center: ['50%', '40%'],
        data: validRoomTypes,
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}: {c} 单\n{d}%',
          fontSize: 12
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          },
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true,
          length: 15,
          length2: 10,
          smooth: true
        },
        color: ['#5470c6', '#91cc75', '#ee6666', '#fac858', '#73c0de', '#3ba272', '#fc8452', '#9a60b4']
      }
    ]
  };
});

// 趋势图表配置
const trendOption = computed(() => {
  // 优化趋势图展示
  const fewDataPoints = orderData.trendData.dates.length <= 3;
  const barWidth = fewDataPoints ? 60 : 'auto';
  
  // 确保日期按月份格式化显示
  const formattedDates = orderData.trendData.dates.map(date => {
    // 如果是YYYY-MM格式，保持不变
    if (/^\d{4}-\d{2}$/.test(date)) {
      return date;
    }
    // 如果是YYYY-MM-DD格式，转换为YYYY-MM
    else if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
      return date.substring(0, 7);
    }
    return date;
  });
  
  // 定义月度数据类型
  interface MonthlyDataItem {
    orderCount: number;
    revenue: number;
  }
  
  // 按月份合并数据
  const monthlyData: Record<string, MonthlyDataItem> = {};
  formattedDates.forEach((date, index) => {
    if (!monthlyData[date]) {
      monthlyData[date] = {
        orderCount: 0,
        revenue: 0
      };
    }
    monthlyData[date].orderCount += orderData.trendData.orderCounts[index] || 0;
    monthlyData[date].revenue += orderData.trendData.revenue[index] || 0;
  });
  
  // 转换为数组格式
  const monthDates = Object.keys(monthlyData).sort();
  const monthOrderCounts = monthDates.map(date => monthlyData[date].orderCount);
  const monthRevenue = monthDates.map(date => monthlyData[date].revenue);
  
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['订单数量', '收入金额']
    },
    xAxis: [
      {
        type: 'category',
        data: monthDates,
        axisPointer: {
          type: 'shadow'
        },
        axisLabel: {
          interval: 0,
          rotate: monthDates.length > 4 ? 30 : 0, // 数据多时才旋转标签
          formatter: (value: string) => {
            // 如果是YYYY-MM格式，转换为更友好的显示
            if (/^\d{4}-\d{2}$/.test(value)) {
              const [year, month] = value.split('-');
              return `${year}年${month}月`;
            }
            return value;
          }
        },
        axisLine: {
          show: true
        },
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '订单数量',
        position: 'left',
        axisLabel: {
          formatter: '{value} 单'
        },
        min: fewDataPoints ? Math.max(0, Math.min(...monthOrderCounts) - 1) : null,
        minInterval: 1
      },
      {
        type: 'value',
        name: '收入金额',
        position: 'right',
        axisLabel: {
          formatter: '¥{value}'
        },
        min: fewDataPoints ? Math.max(0, Math.min(...monthRevenue) - 100) : null
      }
    ],
    series: [
      {
        name: '订单数量',
        type: 'bar',
        data: monthOrderCounts,
        barWidth: barWidth,
        barMaxWidth: 100, // 设置柱子最大宽度
        barGap: '30%', // 增加柱子间距
        itemStyle: {
          color: '#5470c6'
        },
        // 少量数据点时添加标签
        label: {
          show: fewDataPoints || monthDates.length <= 12,
          position: 'top',
          formatter: '{c} 单',
          fontSize: 14
        }
      },
      {
        name: '收入金额',
        type: 'line',
        yAxisIndex: 1,
        data: monthRevenue,
        itemStyle: {
          color: '#ee6666'
        },
        lineStyle: {
          width: 3,
          shadowColor: 'rgba(0,0,0,0.3)',
          shadowBlur: 10,
          shadowOffsetY: 8
        },
        symbol: 'circle',
        symbolSize: fewDataPoints ? 12 : 8, // 少量数据点时增大标记大小
        // 少量数据点时添加标签
        label: {
          show: fewDataPoints || monthDates.length <= 12,
          position: 'top',
          formatter: '¥{c}',
          fontSize: 14
        }
      }
    ],
    grid: {
      left: '3%',
      right: '8%',
      bottom: '3%',
      containLabel: true
    },
    dataZoom: fewDataPoints ? [] : [ // 少量数据点时不显示缩放控件
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100
      }
    ]
  };
});

// 获取周期标题
const periodTitle = computed(() => {
  if (dataPeriod.value === 'month') {
    return '月度';
  } else if (dataPeriod.value === 'quarter') {
    return '季度';
  } else if (dataPeriod.value === 'year') {
    return '年度';
  }
  return '';
});
</script>

<style scoped>
.order-statistics-container {
  padding: 24px;
  background-color: #f5f7f9;
  min-height: calc(100vh - 100px);
}

.statistics-header-section {
  margin-bottom: 24px;
}

.statistics-title-section {
  margin-bottom: 24px;
}

.page-title {
  font-size: 22px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #1f2937;
}

.page-description {
  color: #6b7280;
  margin: 0;
  font-size: 14px;
}

.statistics-filters {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 20px;
}

.filter-item {
  display: flex;
  align-items: center;
}

.filter-label {
  white-space: nowrap;
  margin-right: 12px;
  color: #4b5563;
  font-weight: 500;
}

.date-picker {
  width: 280px;
}

.period-selector {
  margin-right: 0;
}

.action-item {
  margin-left: auto;
}

.chart-row {
  margin-bottom: 24px;
}

.chart-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  height: 100%;
  background-color: #fff;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.chart-header h3 {
  font-size: 16px;
  font-weight: 500;
  margin: 0;
  color: #1f2937;
}

.chart-container {
  height: 380px;
  padding: 8px;
}

/* 特别为饼图设置更大的高度 */
.chart-row:nth-child(3) .chart-container {
  height: 400px;
}

.chart {
  height: 100%;
  width: 100%;
}

/* 中等屏幕 */
@media (max-width: 992px) {
  .action-item {
    margin-left: 0;
  }
}

/* 小屏幕 */
@media (max-width: 768px) {
  .order-statistics-container {
    padding: 16px;
  }
  
  .statistics-filters {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .filter-item {
    flex-direction: column;
    align-items: flex-start;
    width: 100%;
  }
  
  .filter-label {
    margin-right: 0;
    margin-bottom: 8px;
    width: 100%;
  }
  
  .date-picker {
    width: 100%;
  }
  
  .period-selector {
    width: 100%;
  }
  
  .chart-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .chart-header h3 {
    margin-bottom: 12px;
  }
  
  .chart-container {
    height: 350px;
  }
  
  .chart-row:nth-child(3) .chart-container {
    height: 380px;
  }
}
</style>